﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;
using System.Collections.Generic;
using System.Web.Services;

public partial class JOINT_frmJ_TraineeDiplomaInput : System.Web.UI.Page
{
    private int? currentId = null;
    protected void Page_Load(object sender, EventArgs e)
    {

        ((JOINT_MstPage_JOINT)this.Master).changeTitle("入学情報（保有資格）登録");
        ((JOINT_MstPage_JOINT)this.Master).HideLiArea("input");
        if (Session["役"] == null || Session["役"].ToString() == "")
        {
            Response.Redirect("~/frmD_Login.aspx");
        }
        if (Session["ID"] == null)
            Response.Redirect("frmJ_TraineeEnterSchoolSearch.aspx");

        if (!IsPostBack)
        {
            ShowGrid();
            this.getDD1_資格免許コード();
            this.DataColumnView();
            btn_次登録.Visible = true;
            btn_更新.Visible = false;

        }
        ddl_資格免許コード.Focus();
        btn_終了.Enabled = false;
        if (Session["終了Status"] == null)
        {
            Session.Add("終了Status", false);
            btn_終了.Enabled = (bool)Session["終了Status"];
        }

        validateddl_資格免許コード.ErrorMessage = GetError("ER00001");
        validateddl社内外区分.ErrorMessage = GetError("ER00001");
        validatetxt_受検年月日.ErrorMessage = GetError("ER00001");
        validatetxt_取得年月日.ErrorMessage = GetError("ER00001");
        CustomValidator1.ErrorMessage = GetError("ER00005");
        CustomValidator3.ErrorMessage = GetError("ER00009");
        RegularExpressionValidator1.ErrorMessage = GetError("ER00006");
        //CustomValidator5.ErrorMessage = "受検年月日" + GetError("ER00009");
        regular2.ErrorMessage = GetError("ER00006");
        //ResetForm();
    }
    /// <summary>
    /// EVENT'S BUTTON キャンセル
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_キャンセル_Click(object sender, EventArgs e)
    {
        Response.Redirect("frmJ_TraineeEnterSchoolSearch.aspx");
    }
    /// <summary>
    /// EVENT'S BUTTON 賞罰情報へ
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_賞罰情報へ_Click(object sender, EventArgs e)
    {
        List<List<String>> list = new List<List<String>>();
        String[] varList = Request.Form.AllKeys;
        for (int i = 1; i < varList.Length; i++)
        {
            string controlName = varList[i];
            string value = Request.Params.Get(controlName).Replace("<", "&lt;");
            value = value.Replace(">", "&gt;");
            string serverControlName = controlName.Replace("ctl00$ContentPlaceHolder1$", "");
            List<String> val = new List<String>();
            val.Add(serverControlName);
            val.Add(value);
            list.Add(val);
        }

        Session["listValue"] = list;
        Response.Redirect("frmJ_TraineeRewPunInput.aspx");
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }
    /// <summary>
    /// EVENT'S BUTTON リセット
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_リセット_Click(object sender, EventArgs e)
    {
        ResetForm();
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }
    /// <summary>
    /// BIND DATA INTO DROPDOWNLIST(DD1_資格免許コード)
    /// </summary>
    public void getDD1_資格免許コード()
    {
        資格免許コードManager frm = new 資格免許コードManager();
        DataTable dt = new DataTable();
        dt = frm.Select_DDL資格免許コード_frmJ_TraineeDiplomaInput();
        if (dt.Rows.Count > 0)
        {
            ddl_資格免許コード.DataSource = dt;
            ddl_資格免許コード.DataTextField = "資格免許名";
            ddl_資格免許コード.DataValueField = "ID";
            ddl_資格免許コード.DataBind();

            ListItem 選択 = new ListItem("[選択]", "-1");
            ddl_資格免許コード.Items.Insert(0, 選択);
        }
       ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }
    /// <summary>
    /// BIND DATA INTO GRIDVIEW
    /// </summary>
    public void ShowGrid()
    {
        int 社員ID = Int32.Parse(Session["ID"].ToString());
        DataTable dt = new DataTable();
        保有資格情報Manager frm = new 保有資格情報Manager();
        dt = frm.ShowGrid保有資格情報(社員ID);
        DataColumn col = new DataColumn();
        col.DataType = System.Type.GetType("System.Int32");
        col.ColumnName = "IsInit";
        dt.Columns.Add(col);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["IsInit"] = "3";
        }


        if (dt.Rows.Count > 0)
        {
            grv1.Visible = false;
            grv.Visible = true;
            grv.DataSource = dt;
            ViewState["CurrentTable"] = dt;
            grv.DataBind();
        }
        else
        {
            grv1.Visible = true;
            grv.Visible = false;
            grv.DataSource = dt;
            ViewState["CurrentTable"] = dt;
            AppCode_Common.ShowEmtyGrid<本社履歴>(grv1, 4, "データがありません。", "");
        }

    }
    public void DataColumnView()
    {
        try
        {
            DataTable dtv = new DataTable();
            DataColumn col;

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.Int32");
            col.ColumnName = "資格受検コード";
            dtv.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.String");
            col.ColumnName = "資格免許名";
            dtv.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.Boolean");
            col.ColumnName = "社内外区分";
            dtv.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.DateTime");
            col.ColumnName = "受検年月日";
            dtv.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.DateTime");
            col.ColumnName = "取得年月日";
            dtv.Columns.Add(col);

            ViewState["CurrentTable1"] = dtv;
        }
        catch { }
    }
    /// <summary>
    /// ADD NEW ROW FOR GRIDVIEW
    /// </summary>
    protected void AddNewRow()
    {
        try
        {
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                grv1.Visible = false;
                grv.Visible = true;
                drCurrentRow = dtCurrentTable.NewRow();
                drCurrentRow["資格免許コード"] = ddl_資格免許コード.SelectedValue.ToString();
                drCurrentRow["資格免許名"] = ddl_資格免許コード.SelectedItem.ToString();
                string a = ddl社内外区分.SelectedValue.ToString();
                if (a == "0")
                {

                    drCurrentRow["社内外区分"] = "False";
                }
                if (a == "1")
                {
                    drCurrentRow["社内外区分"] = "True";
                }
                drCurrentRow["受検年月日"] = txt_受検年月日.Text.ToString();
                drCurrentRow["取得年月日"] = txt_取得年月日.Text.ToString();

                drCurrentRow["IsInit"] = "0";
                dtCurrentTable.Rows.Add(drCurrentRow);

                DataView dv = new DataView(dtCurrentTable);
                dv.Sort = "IsInit";
                ViewState["CurrentTable"] = dv.ToTable();
                grv.DataSource = dv;
                grv.DataBind();
                Session.Add("終了Status", true);
            }

        }
        catch { }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }

    public void DataCurrentTable()
    {
        try
        {
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable1"];
                grv1.Visible = false;
                grv.Visible = true;
                DataRow drCurrentRow = null;

                drCurrentRow = dt.NewRow();
                drCurrentRow["資格免許コード"] = ddl_資格免許コード.SelectedValue.ToString();
                drCurrentRow["資格免許名"] = ddl_資格免許コード.SelectedItem.ToString();
                drCurrentRow["社内外区分"] = ddl社内外区分.Text.ToString();
                drCurrentRow["受検年月日"] = txt_取得年月日.Text.ToString();
                drCurrentRow["取得年月日"] = txt_取得年月日.Text.ToString();

                ViewState["CurrentTable1"] = dt;

            }
        }
        catch { }
    }
    /// <summary>
    /// CONVERT DATE
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string ConvertDate(string str)// ham convert nagy thang nam.
    {
        if (str == "")
        {
            return str = "";
        }
        else
        {
            string date = str;
            DateTime d1 = DateTime.Parse(date);
            d1.Year.ToString();
            return date = d1.ToString("yyyy年MM月dd日");
        }
    }
    /// <summary>
    /// CONVERT STRING
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string ConvertString(string str)// convert chuoi
    {
        if (str.Equals("False"))
            return "社内";
        else return "社外";
    }
    /// <summary>
    /// ENVET'S BUTTON 終了
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_終了_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataView dv = new DataView(dt);
            dv.Sort = "ID DESC";

            保有資格情報Manager tns = new 保有資格情報Manager();
            if (ViewState["CurrentTable1"] != null)
            {
                foreach (DataRow dataRow1 in dv.Table.Rows)
                {
                    int id = Int32.Parse(dataRow1["IsInit"].ToString());
                    if (id == 0 || id == 1)
                    {
                        int 資格免許コード = Int32.Parse(dataRow1["資格免許コード"].ToString());
                        string 資格免許名 = dataRow1["資格免許名"].ToString();
                        Boolean 社内外区分 = Boolean.Parse(dataRow1["社内外区分"].ToString());
                        DateTime 受検年月日 = DateTime.Parse(dataRow1["受検年月日"].ToString());
                        DateTime 取得年月日 = DateTime.Parse(dataRow1["取得年月日"].ToString());
                        int 社員ID = Int32.Parse(Session["ID"].ToString());
                        保有資格情報 obj = new 保有資格情報();
                        obj.資格免許コード1 = 資格免許コード;
                        obj.資格免許名 = 資格免許名;
                        obj.社内外区分 = 社内外区分;
                        obj.受検年月日 = 受検年月日;
                        obj.取得年月日 = 取得年月日;
                        obj.社員ID = 社員ID;
                        obj.廃止区分 = 0;
                        tns.Insert_frmJ_TraineeDiplomaInput(obj);
                    }
                    if (id == 2 && Session["Array"] != null)
                    {
                        List<String> myAl1 = (List<String>)Session["Array"];
                        foreach (string str in myAl1)
                        {
                            int temp = Int32.Parse(dataRow1["ID"].ToString());
                            if (Int32.Parse(str) == temp)
                            {
                                int 資格免許コード = Int32.Parse(dataRow1["資格免許コード"].ToString());
                                string 資格免許名 = dataRow1["資格免許名"].ToString();
                                Boolean 社内外区分 = Boolean.Parse(dataRow1["社内外区分"].ToString());
                                DateTime 受検年月日 = DateTime.Parse(dataRow1["受検年月日"].ToString());
                                DateTime 取得年月日 = DateTime.Parse(dataRow1["取得年月日"].ToString());
                                保有資格情報 oj = new 保有資格情報();
                                oj.資格免許コード1 = 資格免許コード;
                                oj.資格免許名 = 資格免許名;
                                oj.社内外区分 = 社内外区分;
                                oj.受検年月日 = 受検年月日;
                                oj.取得年月日 = 取得年月日;
                                oj.ID = temp;
                                tns.Update_frmJ_TraineeDiplomaInput(oj);
                            }
                        }
                    }
                }
                Session.Add("終了Status", null);
            }
            this.ShowGrid();
            dt.Rows.Clear();
            btn_終了.Enabled = false;
            btn_次登録.Visible = true;
            btn_更新.Visible = false;
            Session.Remove("Array");

        }
        catch
        {

        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
        //Response.Redirect("frmJ_TraineeEnterSchoolSearch.aspx");
    }
    /// <summary>
    /// ENVETN'S BUTTON 次登録
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_次登録_Click(object sender, EventArgs e)
    {
        CustomValidator3.Validate();
        if (!CustomValidator3.IsValid) return;
        btn_終了.Enabled = true;
        AddNewRow();
        DataCurrentTable();
        if (Page.IsValid)
        {
            ResetForm();
        }
        else
        {
            ShowGrid();
        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    
    }
    /// <summary>
    /// RESET FORM
    /// </summary>
    public void ResetForm()
    {
        ddl_資格免許コード.SelectedValue = "-1";
        ddl社内外区分.SelectedValue = "-1";
        txt_受検年月日.Text = "";
        txt_取得年月日.Text = "";
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    
    }
    protected void ItemView_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.Equals("doubleClick"))
            {
                string ID = grv.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();// Int32.Parse((e.CommandArgument).ToString());
                Session["temp"] = ID.ToString();
                System.Collections.Generic.List<String> myAl = new List<String>();
                if (Session["Array"] != null)
                {
                    myAl = (System.Collections.Generic.List<String>)Session["Array"];
                }
                myAl.Add(ID.ToString());
                Session["Array"] = myAl;
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                foreach (DataRow dataRow1 in dt.Rows)
                {
                    string IDtam = (dataRow1["ID"].ToString());
                    if (ID == IDtam)
                    {
                        ddl_資格免許コード.SelectedValue = dataRow1["資格免許コード"].ToString();
                        Session.Add("CurrentId", dataRow1["資格免許コード"].ToString());
                        if (dataRow1["社内外区分"].ToString() == "False")
                        {
                            ddl社内外区分.SelectedValue = "0";
                        }
                        if (dataRow1["社内外区分"].ToString() == "True")
                        {
                            ddl社内外区分.SelectedValue = "1";
                        }
                        string date = dataRow1["受検年月日"].ToString();
                        string date1 = dataRow1["取得年月日"].ToString();
                        DateTime time = DateTime.Parse(date);
                        DateTime time1 = DateTime.Parse(date1);
                        date = time.ToString("yyyy/MM/dd");
                        date1 = time1.ToString("yyyy/MM/dd");
                        txt_受検年月日.Text = date;
                        txt_取得年月日.Text = date1;
                    }
                }
                btn_更新.Visible = true;
                btn_次登録.Visible = false;
            }
        }
        catch { }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    
    }
    /// <summary>
    /// EVENT'S BUTTON 更新
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_更新_Click(object sender, EventArgs e)
    {
        try
        {
            btn_次登録.Visible = true;
            btn_更新.Visible = false;

            string id = Session["temp"].ToString();
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            foreach (DataRow row1 in dtCurrentTable.Rows)
            {
                int IDtam = Int32.Parse(row1["ID"].ToString());
                if (Int32.Parse(id) == IDtam)
                {
                    row1["資格免許コード"] = ddl_資格免許コード.SelectedValue.ToString();
                    row1["資格免許名"] = ddl_資格免許コード.SelectedItem.ToString();
                    string a = ddl社内外区分.SelectedValue.ToString();
                    if (a == "0")
                    {

                        row1["社内外区分"] = "False";
                    }
                    if (a == "1")
                    {
                        row1["社内外区分"] = "True";
                    }
                    row1["受検年月日"] = txt_受検年月日.Text.Trim().ToString();
                    row1["取得年月日"] = txt_取得年月日.Text.Trim().ToString();
                    //row1["IsInit"] = "1";
                    if (row1["IsInit"].ToString() == "3")
                    {
                        row1["IsInit"] = "2";
                    }
                    if (row1["IsInit"].ToString() == "0")
                    {
                        row1["IsInit"] = "1";
                    }
                }
            }
            DataView dv = new DataView(dtCurrentTable);
            ViewState["CurrentTable"] = dtCurrentTable;
            dv.Sort = "IsInit";
            ViewState["CurrentTable"] = dv.ToTable();
            grv.DataSource = dv;
            grv.DataBind();
            btn_終了.Enabled = true;
            ResetForm();
            Session.Add("CurrentId", null);
        }
        catch { }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    
    }
    protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            e.Row.Attributes.Add("ondblclick", "javascript:__doPostBack('ctl00$ContentPlaceHolder1$grv','doubleClick$" + e.Row.RowIndex + "')");

            int ID = Int32.Parse(e.Row.Cells[5].Text);
            if (ID == 0 || ID == 1)
            {
                e.Row.CssClass = "insert";
                //e.Row.BackColor = System.Drawing.Color.LightPink;
                //e.Row.ForeColor = System.Drawing.Color.Maroon;
            }
            if (ID == 2)
            {
                e.Row.CssClass = "update";
                //e.Row.BackColor = System.Drawing.Color.Chocolate;
                //e.Row.ForeColor = System.Drawing.Color.Maroon;
            }

        }
    }
    /// <summary>
    /// GET ERROR MESSAGE
    /// </summary>
    /// <param name="errorid"></param>
    /// <returns></returns>
    public String GetError(string errorid) // ham dung de lay ma loi hien thi thong tin cua loi do.
    {
        Error er = new Error();
        er.ErrorID = errorid;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        return dt.Rows[0][2].ToString();
    }
    /// <summary>
    /// CHECK ID EXIST
    /// </summary>
    /// <param name="source"></param>
    /// <param name="args"></param>
    protected void CustomValidator3_ServerValidate(object source, ServerValidateEventArgs args)
    {
        //Kiem tra trung id ///////////////////////////////////////////////////////////////
        if (btn_更新.Visible == true)
        {
            string selectId = ddl_資格免許コード.SelectedValue.ToString();
            var currentId = Session["currentId"].ToString();
            if (!selectId.Equals(currentId))
            {
                args.IsValid = true;
                int subId = Int32.Parse(ddl_資格免許コード.SelectedValue.ToString());
                DataTable dt = (DataTable)ViewState["CurrentTable"];

                foreach (DataRow row in dt.Rows)
                {
                    int id2 = int.Parse(row["資格免許コード"].ToString());
                    if (subId == id2)
                    {
                        args.IsValid = false;
                    }
                }
            }
        }
        else
        {
            args.IsValid = true;
            int subId = Int32.Parse(ddl_資格免許コード.SelectedValue.ToString());
            DataTable dt = (DataTable)ViewState["CurrentTable"];

            foreach (DataRow row in dt.Rows)
            {
                int id2 = int.Parse(row["資格免許コード"].ToString());
                if (subId == id2)
                {
                    args.IsValid = false;
                }
            }
        }

    }
    protected void grv_PageIndexChanging(object sender, GridViewPageEventArgs e)// phan trang.
    {
        grv.PageIndex = e.NewPageIndex;
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        DataView dv = new DataView(dt);
        dv.Sort = "ID DESC";
        grv.DataSource = dv;
        grv.DataSource = dt;
        grv.DataBind();
    }
}
